package auto.app.service.impl;

import auto.app.controller.from.ResultDetailFrom;
import auto.app.controller.info.ResultInfo;
import auto.app.dao.CaseDao;
import auto.app.exetion.MainExection;
import auto.app.model.*;
import auto.app.dao.ResultDao;
import auto.app.service.AutoResultDetailService;
import auto.app.service.ResultService;
import auto.app.service.TestCollectionService;
import auto.app.util.CommonUtil;
import auto.app.util.UserGetAccount;
import auto.app.vo.TestReportVo;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import static auto.app.exetion.MainExetionMessage.*;

/**
 * <p>
 * 测试合集测试结果 服务实现类
 * </p>
 *
 * @author 杨森
 * @since 2022-07-20
 */
@Service
public class ResultServiceImpl extends ServiceImpl<ResultDao, Result> implements ResultService {

    @Autowired
    CaseDao caseDao;

    @Autowired
    TestCollectionService testCollectionService;

    @Autowired
    AutoResultDetailService autoResultDetailService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addResult(Result result) {
        QueryWrapper<Result> queryWrapper = new QueryWrapper<>();
        //通过case_id查询
        queryWrapper.eq("case_id", result.getCaseId()).eq("collection_id", 0);
        Result result1 = this.getOne(queryWrapper);
        if (result1 != null) {
            result.setId(result1.getId());
            baseMapper.updateById(result);
            AutoResultDetail autoResultDetail = CommonUtil.copyOne(result, AutoResultDetail.class);
            autoResultDetail.setResultId(result1.getId());
            autoResultDetail.setCreateName(UserGetAccount.getAccountName());
            autoResultDetail.setCreateId(UserGetAccount.getAccountId());
            autoResultDetailService.save(autoResultDetail);
            return true;
        }
        baseMapper.insert(result);
        AutoResultDetail autoResultDetail = CommonUtil.copyOne(result, AutoResultDetail.class);
        autoResultDetail.setResultId(result.getId());
        autoResultDetail.setCreateName(UserGetAccount.getAccountName());
        autoResultDetail.setCreateId(UserGetAccount.getAccountId());
        autoResultDetailService.save(autoResultDetail);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addTestCollection(Result result) {
        QueryWrapper<Result> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("case_id", result.getCaseId());
        queryWrapper.eq("collection_id", result.getCollectionId());
        Result result1 = this.getOne(queryWrapper);
        if (result1 != null) {
            result.setId(result1.getId());
            baseMapper.updateById(result);
            return true;
        }
        baseMapper.insert(result);
        return true;
    }

    @Override
    public ResultInfo detali(ResultDetailFrom resultDetailFrom) throws MainExection {
//        LambdaQueryWrapper<Result> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(Result::getCaseId,resultDetailFrom.getCaseId())
//                .eq(Result::getCollectionId,resultDetailFrom.getCollectionId())
//                .orderByDesc(Result::getCreateDate)
//                .last("limit 0,1");
        QueryWrapper<Result> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("case_id", resultDetailFrom.getCaseId());
        queryWrapper.eq("collection_id", resultDetailFrom.getCollectionId());
        Result result = baseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNull(result)) {
            throw new MainExection(RESULTSELECTERROR.getCode(), RESULTSELECTERROR.getMsg());
        }
        ResultInfo resultInfo = CommonUtil.copyOne(result, ResultInfo.class);
        //对resultInfo进行处理
        return dataFull(resultInfo);
    }

    private ResultInfo dataFull(ResultInfo resultInfo){
        if ("S".equals(resultInfo.getStatus())){
            resultInfo.setStatusMenus("成功");
        }else {
            resultInfo.setStatusMenus("失败");
        }

        if (resultInfo.getCollectionId()==0){
            resultInfo.setCollectionName("无");
        }else{
            TestCollection byId = testCollectionService.getById(resultInfo.getCollectionId());
            resultInfo.setCollectionName(byId.getCollectionName());
        }
        CaseInterface caseInterface = caseDao.selectById(resultInfo.getCaseId());
        resultInfo.setCaseName(caseInterface.getCaseName());
        return resultInfo;
    }

    @Override
    public List<ResultInfo> detailList(Integer collectionId) throws MainExection {

        QueryWrapper<Result> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("collection_id", collectionId);
        List<Result> list = list(queryWrapper);
        if (list == null && list.size() == 0) {
            throw new MainExection(SELECTMYSQLCOLLECTIONCASE.getCode(), SELECTMYSQLCOLLECTIONCASE.getMsg());
        }
        return CommonUtil.copyList(list, ResultInfo.class);
    }

    @Override
    public List<TestReportVo> export(Integer collectionId) throws MainExection {
        //查询当前测试合集下的结果
        LambdaQueryWrapper<Result>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Result::getCollectionId,collectionId);
//        QueryWrapper<Result> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("collection_id", collectionId);
        List<Result> list = list(queryWrapper);
        if (list.size() == 0) {
            throw new MainExection(SELECTMYSQLCOLLECTIONCASE.getCode(), SELECTMYSQLCOLLECTIONCASE.getMsg());
        }
        //将返回结果存在map中
        HashMap<Integer, Result> mapList = new HashMap<>();
        list.forEach(result -> mapList.put(result.getCaseId(), result));
        //提取返回结果中的测试用例id集合
        List<Integer> collect = list.stream().map(Result::getCaseId).distinct().collect(Collectors.toList());
        //查询测试用例详情
        List<CaseDaoDto> caseDaoDtos = caseDao.listExecute(collect);
        if ( caseDaoDtos.size() == 0) {
            throw new MainExection(CASEERROR.getCode(), CASEERROR.getMsg());
        }
        //复制成vo类
        List<TestReportVo> testReportVos = CommonUtil.copyList(caseDaoDtos, TestReportVo.class);
        //vo类中赋值返回结果的信息
        testReportVos.forEach(testReportVo -> {
            Result result = mapList.get(testReportVo.getCaseId());
            if (result != null) {
                testReportVo.setCollectionId(result.getCollectionId());
                testReportVo.setStatus(result.getStatus());
                testReportVo.setResult(result.getResult());
                testReportVo.setMessage(result.getMessage());
            }
        });
        return testReportVos;
    }
}
